import { _decorator, Component, Node, BoxCollider2D, CircleCollider2D, Contact2DType, IPhysics2DContact, Sprite, Vec3 } from 'cc';
import { BasicComponet } from '../../Init/Basic/BasicComponet';
import { GlobalConfig } from '../../Init/Config/GlobalConfig';
import { AudioEnum } from '../../Init/SystemAudio/AudioEnum';
import { AudioSystem } from '../../Init/SystemAudio/AudioSystem';
import { StorageSystem } from '../../Init/SystemStorage/StorageSystem';
import GlobalPool from '../../Init/Tools/GlobalPool';
const { ccclass, property } = _decorator;

@ccclass('AwardKey2d')
export class AwardKey2d extends BasicComponet {
    _isCollion = false;
    collider: BoxCollider2D = null;

    onEnable() {
        // 注册单个碰撞体的回调函数
        this.collider = this.getComponent(BoxCollider2D);
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    setData(d: { parent: Node, p: Vec3 }) {
        this.node.parent = d.parent;
        this.node.setPosition(d.p);
        this._isCollion = false;

        let sp = this.node.getComponent(Sprite);
        if (sp) {
            sp.enabled = GlobalConfig.isShow2dCollider;
        }
    }

    onDisable() {
        if (this.collider) {
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
        }
    }

    _zombieGroup = 1 << 6;
    onBeginContact(selfCollider: BoxCollider2D, otherCollider: CircleCollider2D, contact: IPhysics2DContact | null) {
        if (!this._isCollion && otherCollider.group == this._zombieGroup) {
            this._isCollion = true;
            //
            setTimeout(() => {
                GlobalPool.put(this.node);
            }, 0);

            StorageSystem.setData((d) => {
                d.userAssets.keyNum++;
            }, true);
            StorageSystem.updateToAssets();

            AudioSystem.playEffect(AudioEnum.getLvKey);
        }
    }

}

